package com.moneycollect.webspider.common;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuhuiqian
 * @since 2021/11/30 20:20
 */
public class EasyExcelListConvertor implements Converter<List<String>> {
    @Override
    public Class<List> supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public List convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(StringUtils.isBlank(cellData.getStringValue())) {
            return new ArrayList();
        }

        var parts = cellData.getStringValue().split(",");
        var r = new ArrayList<String>(List.of(parts));
        return r;
    }

    @Override
    public WriteCellData<?> convertToExcelData(List value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        List list = value;
        if(list == null) {
            list = new ArrayList();
        }

        var val = String.join(",", list);
        return new WriteCellData<>(val);
    }
}
